package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import servise.userRegisterService;

public class UserRegisterDao {
	private String driver="com.mysql.jdbc.Driver";
	private String url="jdbc:mysql://10.2.132.41:3306/mydatabase?useUnicode=true&characterEncoding=utf-8";
	private String user="root";
	private String password="sa";
	private String sql;
	Connection con ;
	Statement sta;
	ResultSet rs ;
	public UserRegisterDao() {
		super();
	}
	
	public void getConnection(){
		try {
			Class.forName(driver);
			con=DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} 
	
	public void close() {

		try {
			if (rs != null) {
				rs.close();
			}
			if (sta != null) {
				sta.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public int addItem(String sql){
		this.sql = sql;
		try {
			getConnection();
			sta=con.createStatement();
			sta.execute(sql);
			return 1;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}finally{
			close();
		}
		
	}
	
	public userRegisterService selectItem(String sql){
		this.sql = sql;
		userRegisterService urs = new userRegisterService();
		try {
			getConnection();
			sta=con.createStatement();
			rs = sta.executeQuery(sql);
			if(rs.next()){
				urs.setUserName(rs.getString("username"));
				urs.setPassword(rs.getString("password"));
				urs.setHeight(Float.valueOf(rs.getFloat("height")));
				urs.setWeight(Float.valueOf(rs.getFloat("weight")));
				urs.setSex(Integer.valueOf(rs.getInt("sex")));
			}
			return urs;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			close();
		}
		return urs;
	}

}
